package cn.kgc.controller;

import cn.kgc.base.entity.CartSkuInfo;
import cn.kgc.base.vo.OrderItemVo;
import cn.kgc.client.CartSkuInfoFeignClient;
import cn.kgc.commons.util.RedisUtil;
import cn.kgc.commons.util.UserContextHolder;
import cn.kgc.commons.vo.Result;
import cn.kgc.entity.Cart;
import cn.kgc.entity.CartItem;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * @description:
 * @author: 石浩杰
 * @date: 2022-12-16 09:04
 */

@RestController
@RequestMapping("/cart")
@Api(tags = "购物车")
public class CartController {
    @Resource
    private RedisUtil redisUtil;

    @Resource
    private CartSkuInfoFeignClient careSkuInfoFeignClient;

    @GetMapping("/getOrderItemVo")
    @ApiOperation(value = "根据用户id获得购物车中已经被选中的商品的信息",httpMethod = "GET",
            produces = "application/json;charset=utf-8",response = Result.class)
    @ApiImplicitParam(name = "memberId",value = "用户id",dataType = "long",paramType = "query")
    @CrossOrigin
    public List<OrderItemVo> getOrderItemVo(@RequestParam(name = "memberId") long memberId){
        //购物车中的key
        String cartKey=memberId+"cart";
        if (!redisUtil.hasKey(cartKey)){//判断购物车中是否有商品，如果没有商品返回空集合
            return new ArrayList<>();
        }
        //获得购物车中的商品信息 hash(key hkey hvalue)
        Iterator<Object> iterator=redisUtil.getHash(cartKey).values().iterator();
        List<OrderItemVo> result=new ArrayList<>();//返回的订单中的商品信息
        if (iterator.hasNext()){
            CartItem cartItem=(CartItem) iterator.next();
            //判读购物车中的商品是否被选中
            if (cartItem.isCheck()){
                OrderItemVo orderItemVo=new OrderItemVo();
                BeanUtils.copyProperties(cartItem,orderItemVo);
                result.add(orderItemVo);
            }
        }
        return result;
    }


    /**
     * 向购物车中添加商品信息
     * @param skuId
     * @param count
     * @return
     */
    @PostMapping("/save")
    @ApiOperation(value = "向购物车中添加商品信息",httpMethod = "POST",
            produces = "application/json;charest=utf-8",response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "skuId",value = "skuId",paramType = "query",dataType = "Long"),
            @ApiImplicitParam(name = "count",value = "count",paramType = "query",dataType = "int"),
    })
    public boolean saveCartItem(@RequestParam(name = "skuId") Long skuId,
                                @RequestParam(name = "count",defaultValue = "1") Integer count){
        //todo 登录用户的ID
        String userId = UserContextHolder.getInstance().getUserId();
        //key:用户的Id-cart    hk:skuId  hv:count
        String cacheKey=userId+"cart"; //redis中的key
        //hk
        String hk=skuId+"";
        //1 判断购物车中是否已经有该商品
        if (redisUtil.hasKey(cacheKey,hk)) {
            //如果购物车中已经存在该商品,则将商品的数量进行累加
            CartItem cartItem=new CartItem();
            cartItem.setCount(cartItem.getCount()+count);
            redisUtil.putKey(cacheKey,hk,cartItem);;
            return true;
        }
        //2 购物车没有该商品，将商品放入到购物车中

        Result<CartSkuInfo> cartSkuInfoResult = careSkuInfoFeignClient.getCartSkuInfo(skuId);
        if (cartSkuInfoResult.getData()==null) { //服务降级，没有获得商品的信息
            return false;
        }
        CartSkuInfo cartSkuInfo=cartSkuInfoResult.getData();
        CartItem hv=new CartItem();
        hv.setSkuId(cartSkuInfo.getSkuId());
        hv.setSpuId(cartSkuInfo.getSpuId());
        hv.setSkuAttr(cartSkuInfo.getSkuAttr());
        hv.setImage(cartSkuInfo.getImage());
        hv.setTitle(cartSkuInfo.getTitle());
        hv.setPrice(cartSkuInfo.getPrice());
        hv.setCount(count);
        hv.setCheck(true);
        redisUtil.putKey(cacheKey,hk,hv);
        return true;
        //hv  CartItem对象


        //将商品保存到Redis中。hash类型保存数据
        //（1）购物车中已经有该商品，购物车中的商品数量 增加
        //（2）购物车中没有该商品，将商品放入到购物车中
    }

    //2查看购物车的商品
    @GetMapping("/getCart")
    @ApiOperation(value = "查看购物车信息",httpMethod = "GET",
            produces = "application/json;charset=utf-8",response = Result.class)
    @CrossOrigin
    public Cart getCart(){
        Cart cart=new Cart();
        //购物车中的商品种类
        String userId = UserContextHolder.getInstance().getUserId();
        String cacheKey=userId+"cart";
        if (!redisUtil.hasKey(cacheKey)){  //如果redis中没有购物车信息，直接返回一个空的cart对象
            return cart;
        }
        //购物车中的商品种类

        List<CartItem> cartItemList = new ArrayList<>();
        Map<Object, Object> map = redisUtil.getHash(cacheKey);
        Iterator<Object> iterator = map.values().iterator();
        while (iterator.hasNext()) {
            CartItem cartItem = (CartItem) iterator.next();
            cartItemList.add(cartItem);
        }
        cart.setItems(cartItemList);



        //选中商品数量
        //购物中存储的商品信息
        return cart;
    }
    //删除购物车的商品
}
